package br.com.onlinebidding.converter;


import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.com.onlinebidding.facade.ProductFacade;
import br.com.onlinebidding.model.Product;


@FacesConverter(forClass = Product.class,value="productConverter")
public class ProductConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		ProductFacade productFacade = new ProductFacade();
		int productId;

		try {
			productId = Integer.parseInt(arg2);
		} catch (NumberFormatException exception) {
			throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Type the name of a Product and select it (or use the dropdow)", "Type the name of a Product and select it (or use the dropdow)"));
		}

		return productFacade.findProduct(productId);
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

		if (arg2 == null) {
			return "";
		}
		Product product = (Product) arg2;
		return String.valueOf(product.getId());
	}
}
